<template>  
  <div class="message_board">  
    <div class="message-list">  
      <MessageItem v-for="item in msgList" :key="item.id" :data="item" />  
    </div>  
    <div class="btn-wrapper">  
      <el-button type="info" @click="checkLoginAndShowModal">我要留言</el-button> 
    </div>  
  </div>  
  <MessageModal v-model="show" @send="onSend" />  
</template>  

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus';
import MessageList from '@/mock/message';
import MessageItem from '@/components/MessageItem.vue';
import MessageModal from '@/components/MessageModal.vue';

const store = useStore();

const isLoggedIn = computed(() => store.state.isLoggedIn);

const msgList = ref([]);
const loadMessages = () => {
  const savedMessages = localStorage.getItem('messages');
  if (!savedMessages) {
    msgList.value = MessageList;
    saveMessages();
  } else {
    msgList.value = JSON.parse(savedMessages).reverse();
  }
};

const saveMessages = () => {
  localStorage.setItem('messages', JSON.stringify(msgList.value));
};

loadMessages();

const router = useRouter();

const show = ref(false);
const onSend = (message) => {
  message.id = msgList.value.length > 0 ? msgList.value[0].id + 1 : 1;
  msgList.value.unshift(message);
  saveMessages();
  show.value = false;
  ElMessage.success('留言成功');
};

const checkLoginAndShowModal = () => {
  if (!isLoggedIn.value) {
    ElMessageBox.alert('请先登录', '提示', {
      type: 'warning',
      closeOnClickModal: false,
      closeOnHashChange: true,
      callback: action => {
        if (action === 'confirm') {
          router.push('/login');
        }
      }
    });
  } else {
    show.value = true;
  }
};
</script>

<style scoped>  
.message_board {  
  display: flex;  
  flex-direction: column;  
  padding: 15px;  
  background: #fff;  
  border-radius: 10px;  
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);  
  max-width: 92%;  
}  
  
.message-list {  
  flex: 1;
  border-radius: 10px;  
  padding: 20px;  
  overflow-y: auto; 
  background: linear-gradient(to bottom, #f9f9f9, #fff);  
}  
  
.btn-wrapper {  
  margin-top: 20px;  
  text-align: center;  
}  
   
@media (max-width: 600px) {  
  .message_board {  
    padding: 10px;  
  }  
    
  .message-list {  
    padding: 10px;  
  }  
    
  .btn-wrapper {  
    margin-top: 10px;  
  }  
}  
</style>
